﻿import re

import logging
from datetime import datetime

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
from google.appengine.api import mail

from views_common import *
import models

import PyRSS2Gen
import smth_viewpoint as smth

xml_pattern = '''<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>NewSMTH</title>
    <author>
        <name>ldmiao</name>
        <uri>http://ipsmth.appspot.com/</uri>
        <email>ldmiao@gmail.com</email>
    </author>
    <subtitle>NewSMTH Boards</subtitle>
    <id>urn:ipsmth</id>
    <link rel="self" type="application/atom+xml" href="http://ipsmth.appspot.com/stanza/"/>
    %s
</feed>'''

# ##########################################################################################################################
# /stanza/index/
def index(request):
    global xml_pattern
    entries = '''<entry>
		<title>水木特快-同主题</title>
		<id>urn:NewExpress:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/threads/?board_name=NewExpress"/>
		</entry>

		<entry>
		<title>谈情说爱-同主题</title>
		<id>urn:Love:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/threads/?board_name=Love"/>
		</entry>
        <entry>
        <title>WorkLife-同主题</title>
		<id>urn:NewExpress:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/threads/?board_name=WorkLife"/>
		</entry>
		<entry>
		<title>FamilyLife-同主题</title>
		<id>urn:Love:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/threads/?board_name=FamilyLife"/>
		</entry>
        <entry>
		<title>RealEstate_review-同主题</title>
		<id>urn:Love:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/threads/?board_name=RealEstate_review"/>
		</entry>
        <entry>
		<title>GuoJiXue-同主题</title>
		<id>urn:Love:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/threads/?board_name=GuoJiXue"/>
		</entry>
        <entry>
		<title>EconForum-同主题</title>
		<id>urn:Love:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/threads/?board_name=EconForum"/>
		</entry>
        
        
        
        <entry>
        <title>水木特快</title>
		<id>urn:NewExpress:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/posts/?board_name=NewExpress"/>
		</entry>

		<entry>
		<title>谈情说爱</title>
		<id>urn:Love:ipsmth</id>
		<link type="application/atom+xml" href="/stanza/posts/?board_name=Love"/>
		</entry>
        
        <entry>
		<title>井底望天</title>
		<id>urn:skyinwell:ipsmth</id>
		<link type="application/epub+zip" href="/media/skyinwell.epub"/>
        <author><name>skyinwell</name></author>
        <content type="xhtml"><![CDATA[<div>井底望天 大国游戏</div>]]></content>
		</entry>
        
	'''
    xml = xml_pattern%(entries)

    response = HttpResponse(xml)
    response['Content-Type'] = 'text/xml'
    return response

# ##########################################################################################################################
# /stanza/threads/
def threads(request):
    board_name = request.GET.get('board_name', "NewExpress")
    board_id = int(request.GET.get('board_id', '0'))
    #page_num = 0 means as the last page
    page_num = int(request.GET.get('page_num', '0'))
    
    board_id, threads, page_num_real = smth.getThreadList(board_name, page_num)
    
    global xml_pattern
    
    entries = ''
    
    entries += '''\n<entry>\n'''
    entries += '''<title>上一页【%s】</title>\n'''%(str(int(page_num_real)-1))
    entries += '''<id>urn:%s:%s:ipsmth</id>\n'''%(str(board_id), board_name)
    entries += '''<link type="application/atom+xml" href="/stanza/threads/?board_name=%s&amp;page_num=%s"/>\n'''%(board_name, str(int(page_num_real)-1))
    entries += '''</entry>'''
    
    for thread in threads:
        #0:thread_id, 1:title, 2:word_count, 3:thread_url
        entries += '''\n<entry>\n'''
        entries += '''<title>%s</title>\n'''%(thread[1])
        entries += '''<id>urn:%s:%s:ipsmth</id>\n'''%(str(board_id), board_name)
        entries += '''<link type="application/atom+xml" href="/stanza/post/?board_name=%s&amp;board_id=%s&amp;post_id=%s"/>\n'''%(board_name, str(board_id), thread[0])
        entries += '''</entry>'''
    
    entries += '''\n<entry>\n'''
    entries += '''<title>下一页【%s】</title>\n'''%(str(int(page_num_real)+1))
    entries += '''<id>urn:%s:%s:ipsmth</id>\n'''%(str(board_id), board_name)
    entries += '''<link type="application/atom+xml" href="/stanza/threads/?board_name=%s&amp;page_num=%s"/>\n'''%(board_name, str(int(page_num_real)+1))
    entries += '''</entry>'''
    
    xml = xml_pattern%(entries)
    
    response = HttpResponse(xml)
    response['Content-Type'] = 'text/xml'
    return response

# ##########################################################################################################################
# /stanza/posts/
def posts(request):
    board_name = request.GET.get('board_name', "NewExpress")
    board_id = int(request.GET.get('board_id', '0'))
    #page_num = 0 means as the last page
    page_num = int(request.GET.get('page_num', '0'))
    
    logging.info(page_num)
    
    board_id, posts, page_num_real = smth.getPostList(board_name, page_num)
    
    global xml_pattern
    
    entries = ''
    
    entries += '''\n<entry>\n'''
    entries += '''<title>上一页【%s】</title>\n'''%(str(int(page_num_real)-1))
    entries += '''<id>urn:%s:%s:ipsmth</id>\n'''%(str(board_id), board_name)
    entries += '''<link type="application/atom+xml" href="/stanza/posts/?board_name=%s&amp;page_num=%s"/>\n'''%(board_name, str(int(page_num_real)-1))
    entries += '''</entry>'''
    
    for post in posts:
        #0:thread_id, 1:title, 2:word_count, 3:thread_url
        entries += '''\n<entry>\n'''
        #logging.info(post.title.encode('gbk', 'ignore'))
        entries += ('''<title>%s(%s)%s</title>\n'''%(post.title, str(post.word_count), post.tag)).encode('utf-8', 'ignore')
        entries += '''<id>urn:%s:%s:ipsmth</id>\n'''%(str(board_id), board_name)
        entries += '''<link type="application/atom+xml" href="/stanza/post/?board_name=%s&amp;board_id=%s&amp;post_id=%s"/>\n'''%(board_name, str(board_id), str(post.post_id))
        entries += '''</entry>'''
    
    entries += '''\n<entry>\n'''
    entries += '''<title>下一页【%s】</title>\n'''%(str(int(page_num_real)+1))
    entries += '''<id>urn:%s:%s:ipsmth</id>\n'''%(str(board_id), board_name)
    entries += '''<link type="application/atom+xml" href="/stanza/posts/?board_name=%s&amp;page_num=%s"/>\n'''%(board_name, str(int(page_num_real)+1))
    entries += '''</entry>'''
    
    xml = xml_pattern%(entries)
    
    response = HttpResponse(xml)
    response['Content-Type'] = 'text/xml'
    return response
    
    
# ##########################################################################################################################
# /stanza/post/
def post(request):
    board_name = request.GET.get('board_name', "NewExpress")
    board_id = request.GET.get("board_id", None)
    #thread_id = request.GET.get("thread_id", "0")
    post_id = request.GET.get("post_id", None)
    post_type = request.GET.get("post_type", None)
    
    logging.info(post_type)
    
    global xml_pattern
    
    entries = ''
    if board_id and post_id:
        post_id, thread_id, post_title, postContent = getPostContent(board_id, post_id, post_type)
        
        entries = '''\n<entry>\n'''
        entries += '''<title>%s</title>\n'''%(post_title)
        entries += '''<id>urn:%s:%s:ipsmth</id>\n'''%(str(post_id), board_name)
        entries += '''<author><name>NewSMTh</name></author>\n'''
        entries += '''<content type="xhtml"><![CDATA[<div>%s</div>]]></content>\n'''%(postContent)
        #entries += '''<link type="application/epub+zip" href="/library/epub/fendou.epub"/>
        #              <link rel="x-stanza-cover-image-thumbnail" type="image/jpg" href="/thumb/daa55645e1f7b6bec7cf985dfb9720e4.jpg"/>
        #              <link rel="x-stanza-cover-image" type="image/jpg" href="/images/book_cover/fendou.jpg"/>\n'''
        entries += '''</entry>'''
        
    xml = xml_pattern%(entries)
        
    response = HttpResponse(xml)
    response['Content-Type'] = 'text/xml'
    return response

# ##########################################################################################################################
def fs(str):
    if str is None:
        return None
    else:
        return unicode(str, 'utf-8', 'ignore')
        
# ##########################################################################################################################
# get Post Content
def getPostContent(board_id, post_id, post_type):
    
    post_id = smth.getPostId(board_id, post_id, post_type)
    
    post = db.GqlQuery("SELECT * FROM Post WHERE board_id=:1 and post_id=:2", int(board_id), int(post_id)).get()
    
    #logging.info("--------------------------")
    #logging.info(post)
    
    if not post:
        post_id, thread_id, post_title, head, content_text, ref, attachment_html, signature = smth.getPostContent(board_id, post_id)
        #logging.info(post_id)
        
        board_id=int(board_id)
        post_id=int(post_id)
        thread_id=int(thread_id)
        
        head=unicode(head, 'utf-8', 'ignore')
        ref=unicode(ref, 'utf-8', 'ignore')
        attachment_html=unicode(attachment_html, 'utf-8', 'ignore')
        signature=unicode(signature, 'utf-8', 'ignore')
        content_text=unicode(content_text, 'utf-8', 'ignore')
        post_title = unicode(post_title, 'utf-8', 'ignore')
        
        post = models.Post(board_id=board_id, post_id=post_id, thread_id=thread_id, head=head, ref=ref, attachment=attachment_html, signature=signature, content=content_text, title=post_title)
        try:
            post.put()
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
            models.cleanOldPosts()
            mail.send_mail(sender="ipsmth@googleappengine.com",
              to="Demiao Lin <ldmiao@gmail.com>",
              subject="It seems that ipsmth had a OverQuotaError",
              body='''
                Dear Demiao:
                
                Your http://ipsmth.appspot.com just had a OverQuotaError:
                --------------------------------
                '''
                + message +
                '''
                --------------------------------
                
                Please check it if you have time.
                
                From: ipsmth@googleappengine.com''')

    config = db.GqlQuery("SELECT * FROM Configuration WHERE user=:1", getUser()).get()
    #logging.info(config)
    
    return post.post_id, post.thread_id, post.title, post.toHTML(config)